import sys
import psutil
from pywinauto.application import Application
from pywinauto import clipboard, keyboard


def __get_grid_data(self, is_records=False):
    """ 获取grid里面的数据 """
    time.sleep(API_Config.cfg["sleepC"])  # 等待1秒是 因为等待加载到数据后再去获取grid
    try:
        self.main_wnd.window(control_id=0x417, class_name='CVirtualGridCtrl').set_focus()
    except:
        time.sleep(API_Config.cfg["sleepC"])
        self.main_wnd.window(control_id=0x417, class_name='CVirtualGridCtrl').set_focus()

    keyboard.send_keys('{VK_APPS}')  # 键盘鼠标右键
    time.sleep(API_Config.cfg["sleepA"])
    keyboard.send_keys('c')  # 发送c 软件中的复制功能通过右键实现(ctrl+c快捷键不起作用)
    time.sleep(API_Config.cfg["sleepA"])
    data = clipboard.GetData()  # 读取剪贴板数据
    df = pd.read_csv(io.StringIO(data), delimiter='\t', na_filter=False)
    if is_records:
        return df.to_dict('records')
    else:
        return df


def __select_menu(self, path):
    """ 点击左边菜单 """
    if r"网上股票" not in self.app.top_window().window_text():
        self.app.top_window().set_focus()
        pywinauto.keyboard.send_keys("{ENTER}")
    self.__get_left_menus_handle().get_item(path).click()

if __name__ == '__main__':
    for p in psutil.process_iter():
        if 'xiadan.exe' in p.name().lower():
            app = Application().connect(process=p.pid, backend='win32')
            '''for row in app.element_info:
                print(row.name)
                print(row.title)
                print(row.type)'''
            dlg_spec = app.window(title='网上股票交易系统5.0')
            app.top_window().set_focus()
            #dlg_spec.print_control_identifiers()
            app.__select_menu(['查询[F4]', '资金明细'])
            df = app.__get_grid_data()
            print(df)